package com.dianpingmedia.simulate.controller;

import com.alibaba.fastjson.JSON;
import com.dianpingmedia.common.DspID;
import com.dianpingmedia.common.ErrorCode;
import com.dianpingmedia.common.utils.MiscUtil;
import com.dianpingmedia.common.utils.SmlUtils;
import com.dianpingmedia.proto.ProtoZmeng;
import com.dianpingmedia.simulate.model.*;
import com.google.protobuf.ByteString;
import com.googlecode.protobuf.format.JsonFormat;
import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.dianpingmedia.proto.ProtoZmeng.Device.DeviceType.OUTDOOR_SCREEN;
import static com.dianpingmedia.proto.ProtoZmeng.Device.OsType.ANDROID;

@RestController
public class SimulateController extends AbstractController {

    public static final Integer BASE_CODE = 9000;

    /**
     * 广告素材提交
     *
     * @param request
     * @param result
     * @return
     */
    @RequestMapping("/material/upload")
    public SimulateUploadEntity.Response uploadMaterial(@Validated @RequestBody SimulateUploadEntity.Request request, BindingResult result) {
        SimulateUploadEntity.Response response = new SimulateUploadEntity.Response();
        if (result.hasErrors()) {
            response.setErrorCode(BASE_CODE + ErrorCode.PARAMETER_ERROR.getValue());
            response.setMessgae(result.getFieldError().getDefaultMessage());
        } else if (!SmlUtils.isSupport(request.getUrl())) {
            response.setErrorCode(BASE_CODE + ErrorCode.ENCODING_NOT_SUPPORT.getValue());
            response.setMessgae("The format can't support");
        } else if (StringUtils.isEmpty(request.getMd5()) || request.getWidth() == null || request.getHeight() == null) {
            Object[] whInts = SmlUtils.returnWH(request.getUrl(), configuration.getStorage_directory());
            if (whInts != null) {
                request.setWidth(Integer.valueOf(whInts[0].toString()));
                request.setHeight(Integer.valueOf(whInts[1].toString()));
                if (StringUtils.isEmpty(request.getMd5())) {
                    request.setMd5(whInts[2].toString());
                }
                if (request.getDuration() == null) {
                    request.setDuration(Integer.valueOf(whInts[3].toString()));
                }
            } else {
                response.setErrorCode(BASE_CODE + ErrorCode.NO_RESPONSE.getValue());
                response.setMessgae("THE URL FILE DOWNLOAD ERROR");
                return response;
            }
        }
        return simulateService.uploadMaterial(request);
    }

    /**
     * 查询广告素材
     *
     * @return
     */
    @RequestMapping("/material/query")
    public SimulateArrayResponse<SimulateUploadEntity.Request> queryMaterial(@RequestBody(required = false) SimulateQueryEntity queryRequest) {

        return simulateService.queryMaterial(queryRequest);
    }

    @RequestMapping("/material/delete")
    public SimulateResponse deleteMaterial(@RequestBody SimulateDeleteEntity simulateDeleteEntity) {
        if ((simulateDeleteEntity.getIds() == null || simulateDeleteEntity.getIds().size() == 0) && !simulateDeleteEntity.isAll()) {
            return SimulateResponse.create().setErrorCode(BASE_CODE + ErrorCode.PARAMETER_ERROR.getValue()).setMessage("PARAMETER_ERROR");
        }
        return simulateService.deleteMaterial(simulateDeleteEntity);
    }


    /**
     * 创建广告计划
     *
     * @param request
     * @param result
     * @return
     */
    @RequestMapping("/plan/create")
    public SimulatePlanEntity.Response pushCreate(@Validated @RequestBody SimulatePlanEntity.Request request, BindingResult result) {
        if (result.hasErrors()) {
            SimulatePlanEntity.Response response = new SimulatePlanEntity.Response();
            response.setCode(BASE_CODE + ErrorCode.PARAMETER_ERROR.getValue());
            response.setMessage(result.getFieldError().getDefaultMessage());
            return response;
        }
        SimulatePlanEntity.Response response = transmitTo(request);
        return response;
    }


    @RequestMapping("/getZmtAd.json")
    public String jsonToProtoBuf(@RequestBody ZmAdJsonRequest zmAdRequest) {
        ProtoZmeng.Version version = ProtoZmeng.Version.newBuilder()
                .setMajor(5)
                .setMinor(1)
                .setMicro(1)
                .build();

        ProtoZmeng.Size screenSize = ProtoZmeng.Size.newBuilder()
                .setHeight(zmAdRequest.getScreenHeight())
                .setWidth(zmAdRequest.getWidth())
                .build();

        ProtoZmeng.UdId udId = ProtoZmeng.UdId.newBuilder()
                .setAndroidId(zmAdRequest.getAndroidId() == null ? "" : zmAdRequest.getAndroidId())
                .setImei(zmAdRequest.getImei() == null ? "" : zmAdRequest.getImei())
                .setMac(zmAdRequest.getMac() == null ? "" : zmAdRequest.getMac())
                .build();

        ProtoZmeng.Size adSlotsize = ProtoZmeng.Size.newBuilder()
                .setWidth(zmAdRequest.getWidth())
                .setHeight(zmAdRequest.getHeight())
                .build();

        ProtoZmeng.Device device = ProtoZmeng.Device.newBuilder()
                .setDeviceType(OUTDOOR_SCREEN)
                .setOsType(ANDROID)
                .setOsVersion(version)
                .setModel(ByteString.copyFrom(zmAdRequest.getModel().getBytes()))
                .setVendor(ByteString.copyFrom(zmAdRequest.getVendor().getBytes()))
                .setUdid(udId)
                .setScreenSize(screenSize)
                .build();

        ProtoZmeng.Network.ConnectionType connectionType = ProtoZmeng.Network.ConnectionType.valueOf(0);
        ProtoZmeng.Network.OperatorType operatorType = ProtoZmeng.Network.OperatorType.valueOf(0);
        ProtoZmeng.Network network = ProtoZmeng.Network.newBuilder()
                .setIpv4(zmAdRequest.getIpv4())
                .setConnectionType(connectionType)
                .setOperatorType(operatorType)
                .setCellularId("")
                .build();

        ProtoZmeng.AdSlot adSlot = ProtoZmeng.AdSlot.newBuilder()
                .setDuration(zmAdRequest.getDuration())
                .setType(zmAdRequest.getType())
                .setAdslotSize(adSlotsize)
                .build();


        ProtoZmeng.ZmAdRequest request = ProtoZmeng.ZmAdRequest.newBuilder()
                .setChannelId(zmAdRequest.getChannelId())
                .setScreenId(zmAdRequest.getScreenId())
                .setRequestId(zmAdRequest.getRequestId())
                .setDevice(device)
                .setAdslot(adSlot)
                .setNetwork(network)
                .setToken(zmAdRequest.getToken())
                .build();


        return new JsonFormat().printToString(getZmAd(request));
    }


    /**
     * 众盟请求广告
     *
     * @param request
     * @return
     */
    @RequestMapping("/zmt/api/ad/getAd.do")
    public ProtoZmeng.ZmAdResponse getZmAd(@RequestBody ProtoZmeng.ZmAdRequest request) {
        ProtoZmeng.ZmAdResponse.Builder builder = ProtoZmeng.ZmAdResponse.newBuilder();
        builder.setRequestId(request.getRequestId());
        builder.setChannelId(request.getChannelId());
        int type = request.getAdslot().getType();
        SimulateUploadEntity.Request material = simulateService.queryRandomMaterial(type, DspID.ZMT_DSP_ID);
        if (material != null) {
            builder.setMaterialSrc(material.getUrl());
            builder.setDuration(material.getDuration());
            builder.setCreativeType(material.getMaterialType());
            builder.setMaterialHeight(material.getHeight());
            builder.setMaterialWidth(material.getWidth());
            builder.setFileMd5(material.getMd5());
            builder.setExpirationTime(24 * 60 * 60 * 1000);
            SimulateUploadEntity.Request.Notice[] notices = material.getNotices();
            if (notices != null && notices.length > 0) {
                for (SimulateUploadEntity.Request.Notice notice : notices) {
                    Integer noticeType = notice.getNoticeType();
                    boolean empty = StringUtils.isEmpty(notice.getNoticeUrl());
                    String noticeUrl = noticeUtil.createNoticeUrl(DspID.ZMT_DSP_ID
                            , request.getScreenId()
                            , request.getRequestId()
                            , noticeType
                            , notice.getReturnCode()
                            , notice.getMacros()
                            , material);
                    if (noticeType == 2) {
                        builder.addWinNoticeUrl(empty ? noticeUrl : notice.getNoticeUrl());
                    } else {
                        ProtoZmeng.AdTracking adTracking = ProtoZmeng.AdTracking.newBuilder()
                                .setTrackingEvent(String.valueOf(noticeType))
                                .addTrackingUrl(empty ? noticeUrl : notice.getNoticeUrl())
                                .build();
                        builder.addAdTracking(adTracking);
                    }
                }


                if (builder.getWinNoticeUrlCount() == 0) {
                    builder.addWinNoticeUrl(noticeUtil.createNoticeUrl(DspID.ZMT_DSP_ID
                            , request.getScreenId()
                            , request.getRequestId()
                            , 2
                            , 200
                            , null
                            , material));
                }

                if (builder.getAdTrackingCount() == 0) {
                    ProtoZmeng.AdTracking adStartTracking = ProtoZmeng.AdTracking.newBuilder()
                            .setTrackingEvent("0")
                            .addTrackingUrl(noticeUtil.createNoticeUrl(DspID.ZMT_DSP_ID
                                    , request.getScreenId()
                                    , request.getRequestId()
                                    , 0
                                    , 200
                                    , null
                                    , material))
                            .build();
                    builder.addAdTracking(adStartTracking);

                    ProtoZmeng.AdTracking adEndTracking = ProtoZmeng.AdTracking.newBuilder()
                            .setTrackingEvent("1")
                            .addTrackingUrl(noticeUtil.createNoticeUrl(DspID.ZMT_DSP_ID
                                    , request.getScreenId()
                                    , request.getRequestId()
                                    , 1
                                    , 200
                                    , null
                                    , material))
                            .build();
                    builder.addAdTracking(adEndTracking);
                }
            } else {
                builder.addWinNoticeUrl(noticeUtil.createNoticeUrl(DspID.ZMT_DSP_ID
                        , request.getScreenId()
                        , request.getRequestId()
                        , 2
                        , 200
                        , null
                        , material));

                ProtoZmeng.AdTracking adStartTracking = ProtoZmeng.AdTracking.newBuilder()
                        .setTrackingEvent("0")
                        .addTrackingUrl(noticeUtil.createNoticeUrl(DspID.ZMT_DSP_ID
                                , request.getScreenId()
                                , request.getRequestId()
                                , 0
                                , 200
                                , null
                                , material))
                        .build();
                builder.addAdTracking(adStartTracking);


                ProtoZmeng.AdTracking adEndTracking = ProtoZmeng.AdTracking.newBuilder()
                        .setTrackingEvent("1")
                        .addTrackingUrl(noticeUtil.createNoticeUrl(DspID.ZMT_DSP_ID
                                , request.getScreenId()
                                , request.getRequestId()
                                , 1
                                , 200
                                , null
                                , material))
                        .build();
                builder.addAdTracking(adEndTracking);
            }
            builder.setErrorCode(0);
            if (configuration.zmtConfiguration.getDelay() > 0) {
                try {
                    Thread.sleep(configuration.zmtConfiguration.getDelay());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return builder.build();
        }
        builder.setErrorCode(204);
        return builder.build();
    }


    /**
     * 广告审核
     *
     * @param request
     * @return
     */
    @RequestMapping("/plan/auditResult.json")
    public ZMTReviewEntity.Response materialReview(@Validated @RequestBody ZMTReviewEntity.Request request, BindingResult result) {
        ZMTReviewEntity.Response response = new ZMTReviewEntity.Response();
        if (result.hasErrors()) {
            response.setCode(ErrorCode.PARAMETER_ERROR.getValue());
            response.setMessage(result.getFieldError().getDefaultMessage());
            return response;
        }
        String token = request.getToken();
        if (!token.equals(configuration.zmtConfiguration.getToken())) {
            response.setCode(ErrorCode.PARAMETER_ERROR.getValue());
            response.setMessage("token mismatching");
            return response;
        }
        String sign = request.getSign();
        String contrastSign = MiscUtil.zmengSign(request);
        if (!sign.equals(contrastSign)) {
            response.setCode(ErrorCode.PARAMETER_ERROR.getValue());
            response.setMessage("sign mismatching your sign:" + sign + " my sign:" + contrastSign);
            return response;
        }
        response.setCode(ErrorCode.OK.getValue());
        return response;

    }


//    /**
//     * 资质更新
//     *
//     * @param request
//     * @return
//     */
//    @RequestMapping("/zmt/api/ad/getAd.do")
//    public ZMTCertificateEntity.Response certificateUpdate(@RequestBody ZMTCertificateEntity.Request request, BindingResult result) {
//
//        return null;
//
//    }


    /**
     * 讯飞广告请求
     *
     * @param request
     * @param xProtocolVer
     * @param acceptEncoding
     * @return
     */
    @RequestMapping("/api/request")
    public IFlyGetAdEntity.Response getXfAd(@Validated @RequestBody IFlyGetAdEntity.Request request
            , @RequestHeader(value = "X-protocol-ver", required = false) String xProtocolVer
            , @RequestHeader(value = "Accept-Encoding", required = false) String acceptEncoding
            , BindingResult result, HttpServletRequest httpRequest) {
        IFlyGetAdEntity.Response response = new IFlyGetAdEntity.Response();
        response.setSession_id(httpRequest.getSession().getId());
        if (StringUtils.isEmpty(xProtocolVer) || StringUtils.isEmpty(acceptEncoding)) {
            response.setError_code(String.valueOf(2001));
            return response;
        }

        if (result.hasErrors()) {
            response.setError_code(String.valueOf(ErrorCode.PARAMETER_ERROR.getValue()));
            LOGGER.error(result.getFieldError().getDefaultMessage());
            return response;
        }
        IFlyGetAdEntity.Request.Device device = request.getDevice();
        IFlyGetAdEntity.Request.Imp imp = request.getImp();
        IFlyGetAdEntity.Request.Media media = request.getMedia();

        if (StringUtils.isEmpty(imp.getAd_id())
                || imp.getAd_width() == null
                || imp.getAd_high() == null
                || imp.getPos() == null
                || imp.getUrl_schemes() == null
                //广告位信息判断
                || (StringUtils.isEmpty(media.getMedia_id())
                && (media.getChannel_id() == null
                || media.getSelf_media_id() == null))

                || device.getDv_type() == null
                || device.getOs() == null
                || device.getOsv() == null
                //涉及Android设备的判断
                || (device.getOs().equals("Android")
                && (StringUtils.isEmpty(device.getAdid())
                || StringUtils.isEmpty(device.getImei())
                || StringUtils.isEmpty(device.getMac())))
                //常规设备信息判断
                || device.getNet_type() == null
                || StringUtils.isEmpty(device.getUa())
                || device.getDv_width() == null
                || device.getDv_high() == null
                || device.getDensity() == null
                || StringUtils.isEmpty(device.getVendor())
                || StringUtils.isEmpty(device.getModel())) {

            response.setError_code(String.valueOf(ErrorCode.PARAMETER_ERROR.getValue()));
            return response;
        }
        SimulateUploadEntity.Request material = simulateService.queryRandomMaterial(0, DspID.IFLY_DSP_ID);
        if (material != null) {
            SimulateUploadEntity.Request.Notice[] notices = material.getNotices();
            response.setRes_code(70200);
            ArrayList<IFlyGetAdEntity.Response.Seatbid> seat_bids = new ArrayList<>();
            IFlyGetAdEntity.Response.Seatbid seatbid = new IFlyGetAdEntity.Response.Seatbid();
            seat_bids.add(seatbid);
            response.setSeat_bids(seat_bids);

            seatbid.setSeat_id(request.getReq_id());
            seatbid.setCreate_id(material.getId());
            if (material.getMaterialType() == 1) {
                IFlyGetAdEntity.Response.Seatbid.PictureAd pictureAd = new IFlyGetAdEntity.Response.Seatbid.PictureAd();
                pictureAd.setAd_source_mark("brand");
                pictureAd.setImage_url(material.getUrl());
                pictureAd.setImage_md5(material.getMd5());
                pictureAd.setWidth(material.getWidth());
                pictureAd.setHigh(material.getHeight());
                pictureAd.setPlay_time(material.getDuration() * 1000);
                List<String> imp_urls = new ArrayList<String>();
                if (notices != null) {
                    boolean start = false;
                    boolean end = false;

                    for (SimulateUploadEntity.Request.Notice notice : notices) {
                        Integer noticeType = notice.getNoticeType();
                        String noticeUrl = noticeUtil.createNoticeUrl(DspID.IFLY_DSP_ID,
                                request.getMedia().getMedia_id(),
                                request.getReq_id(),
                                noticeType, notice.getReturnCode(), notice.getMacros(), material);
                        imp_urls.add(noticeUrl);
                        if (noticeType == 0) {
                            start = true;
                        } else if (noticeType == 1) {
                            end = true;
                        }
                    }

                    if (!start) {
                        String startUrl = noticeUtil.createNoticeUrl(DspID.IFLY_DSP_ID,
                                request.getMedia().getMedia_id(),
                                request.getReq_id(),
                                0, 200, null, material);
                        imp_urls.add(startUrl);
                    }
                    if (!end) {
                        String endUrl = noticeUtil.createNoticeUrl(DspID.IFLY_DSP_ID,
                                request.getMedia().getMedia_id(),
                                request.getReq_id(),
                                1, 200, null, material);
                        imp_urls.add(endUrl);
                    }

                } else {
                    String startUrl = noticeUtil.createNoticeUrl(DspID.IFLY_DSP_ID,
                            request.getMedia().getMedia_id(),
                            request.getReq_id(),
                            0, 200, null, material);
                    String endUrl = noticeUtil.createNoticeUrl(DspID.IFLY_DSP_ID,
                            request.getMedia().getMedia_id(),
                            request.getReq_id(),
                            1, 200, null, material);
                    imp_urls.add(startUrl);
                    imp_urls.add(endUrl);

                }
                pictureAd.setImp_urls(imp_urls.toArray(new String[]{}));
                seatbid.setPicture_ad(pictureAd);
            } else {
                IFlyGetAdEntity.Response.Seatbid.VideoAd videoAd = new IFlyGetAdEntity.Response.Seatbid.VideoAd();
                videoAd.setVideo_url(material.getUrl());
                videoAd.setVideo_md5(material.getMd5());
                videoAd.setMtype("brank");
                videoAd.setDuration(material.getDuration() * 1000);
                List<String> imp_urls = new ArrayList<String>();
                if (notices != null) {
                    for (SimulateUploadEntity.Request.Notice notice : notices) {
                        String noticeUrl = noticeUtil.createNoticeUrl(DspID.IFLY_DSP_ID,
                                request.getMedia().getMedia_id(),
                                request.getReq_id(),
                                notice.getNoticeType(), notice.getReturnCode(), notice.getMacros(), material);
                        imp_urls.add(noticeUrl);
                    }
                } else {
                    String startUrl = noticeUtil.createNoticeUrl(DspID.IFLY_DSP_ID,
                            request.getMedia().getMedia_id(),
                            request.getReq_id(),
                            0, 200, null, material);
                    String endUrl = noticeUtil.createNoticeUrl(DspID.IFLY_DSP_ID,
                            request.getMedia().getMedia_id(),
                            request.getReq_id(),
                            1, 200, null, material);
                    imp_urls.add(startUrl);
                    imp_urls.add(endUrl);

                }
                videoAd.setImp_urls(imp_urls.toArray(new String[]{}));
                seatbid.setVideo_ad(videoAd);
            }
            if (configuration.iFlyConfiguration.getDelay() > 0) {
                try {
                    Thread.sleep(configuration.iFlyConfiguration.getDelay());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return response;
        }
        response.setRes_code(70204);
        return response;
    }


    /**
     * 讯飞媒体位同步
     *
     * @param request
     */
    @RequestMapping("/adapi/v2/sync/media")
    public IFlySyncMediaEntity.Response syncMedia(@Validated @RequestBody IFlySyncMediaEntity.Request request, BindingResult result) {
        IFlySyncMediaEntity.Response response = new IFlySyncMediaEntity.Response();
        response.setReturn_code(0);
        if (result.hasErrors()) {
            response.setReturn_code(BASE_CODE + 3);
            String defaultMessage = result.getFieldError().getDefaultMessage();
            LOGGER.error(defaultMessage);
            response.setMessage(defaultMessage);
        } else if (!request.getToken().equals(configuration.iFlyConfiguration.getToken())) {
            response.setReturn_code(1);
            response.setMessage("VERIFY_TOKEN_FAIL");
        } else if (!request.getSign().equals( MiscUtil.iFlySign(MiscUtil.obj2Map(request)))){
            response.setReturn_code(2);
            response.setMessage("VERIFY_SIGN_FAIL");
        }else{
            Map<String, Map<String, String>> message = SmlUtils.iFlySyncMediaReturn(request.getMedias());
            response.setMessage(message);
        }
        return response;
    }

    /**
     * 媒体信息查询接口
     *
     * @param request
     * @param result
     * @return
     */
    @RequestMapping("/adapi/v2/sync/relation")
    public IFlySyncRelationEntity.Response syncRelation(@Validated @RequestBody IFlySyncRelationEntity.Request request, BindingResult result) {
        IFlySyncRelationEntity.Response response = new IFlySyncRelationEntity.Response();
        response.setReturn_code(0);
        if (result.hasErrors()) {
            response.setReturn_code(BASE_CODE + 3);
            String defaultMessage = result.getFieldError().getDefaultMessage();
            LOGGER.error(defaultMessage);
            response.setMessage(defaultMessage);
        } else if (!request.getToken().equals(configuration.iFlyConfiguration.getToken())) {
            response.setReturn_code(1);
            response.setMessage("VERIFY_TOKEN_FAIL");
        } else if (!request.getSign().equals(MiscUtil.iFlySign(MiscUtil.obj2Map(request)))) {
            response.setReturn_code(2);
            response.setMessage("VERIFY_SIGN_FAIL");
        }else{
            response.setMessage(SmlUtils.iFlySyncRelationReturn(request.getRels()));
        }
        return response;
    }

    /**
     * 媒体广告位关联关系同步接口
     *
     * @param request
     * @param result
     * @return
     */
    @RequestMapping("/adapi/v2/sync/request")
    public IFlySyncRequestEntity.Response syncRequest(@Validated @RequestBody IFlySyncRequestEntity.Request request, BindingResult result) {
        IFlySyncRequestEntity.Response response = new IFlySyncRequestEntity.Response();
        response.setReturn_code(0);
        if (result.hasErrors()) {
            response.setReturn_code(BASE_CODE + 3);
            String defaultMessage = result.getFieldError().getDefaultMessage();
            LOGGER.error(defaultMessage);
            response.setMessage(defaultMessage);
        } else if (!request.getToken().equals(configuration.iFlyConfiguration.getToken())) {
            response.setReturn_code(1);
            response.setMessage("VERIFY_TOKEN_FAIL");
        }else if (!request.getSign().equals(MiscUtil.iFlySign(MiscUtil.obj2Map(request)))) {
            response.setReturn_code(2);
            response.setMessage("VERIFY_SIGN_FAIL");
        }
        return response;
    }


    /**
     * 媒体广告位关联关系同步接口
     *
     * @param request
     * @param result
     * @return
     */
    @RequestMapping("/adapi/v2/sync/modifyMedia")
    public IFlySyncMediaEntity.Response modifyMedia(@Validated @RequestBody IFlyModifyMediaEntity.Request request, BindingResult result) {
        IFlySyncMediaEntity.Response response = new IFlySyncMediaEntity.Response();
        response.setReturn_code(0);
        if (result.hasErrors()) {
            response.setReturn_code(BASE_CODE + 3);
            String defaultMessage = result.getFieldError().getDefaultMessage();
            LOGGER.error(defaultMessage);
            response.setMessage(defaultMessage);
        } else if (!request.getToken().equals(configuration.iFlyConfiguration.getToken())) {
            response.setReturn_code(1);
            response.setMessage("VERIFY_TOKEN_FAIL");
        }else if (!request.getSign().equals(MiscUtil.iFlySign(MiscUtil.obj2Map(request)))) {
            response.setReturn_code(2);
            response.setMessage("VERIFY_SIGN_FAIL");
        }
        return response;
    }


    /**
     * 讯飞广告位同步
     *
     * @param request
     */
    @RequestMapping("/adapi/v2/sync/adunit")
    public IFlySyncAdunitEntity.Response syncAdunit(@Validated @RequestBody IFlySyncAdunitEntity.Request request, BindingResult result) {
        IFlySyncAdunitEntity.Response response = new IFlySyncAdunitEntity.Response();
        response.setReturn_code(0);
        if (result.hasErrors()) {
            response.setReturn_code(BASE_CODE + 3);
            String defaultMessage = result.getFieldError().getDefaultMessage();
            LOGGER.error(defaultMessage);
            response.setMessage(defaultMessage);
        } else if (!request.getToken().equals(configuration.iFlyConfiguration.getToken())) {
            response.setReturn_code(1);
            response.setMessage("VERIFY_TOKEN_FAIL");
        }else if (!request.getSign().equals(MiscUtil.iFlySign(MiscUtil.obj2Map(request)))) {
            response.setReturn_code(2);
            response.setMessage("VERIFY_SIGN_FAIL");
        }else{
            response.setMessage(SmlUtils.iFlySyncAdunitReturn(request.getAdunits()));
        }
        return response;
    }


    /**
     * 讯飞审核结果回调
     *
     * @param request
     * @param result
     * @return
     */
    @RequestMapping("/adapi/v1/audit/audit")
    public IFlyReviewEntity.Response iflyReview(@Validated @RequestBody IFlyReviewEntity.Request request, BindingResult result) {
        IFlyReviewEntity.Response response = new IFlyReviewEntity.Response();
        response.setErrorCode(ErrorCode.OK.getValue());
        if (result.hasErrors()) {
            response.setErrorCode(BASE_CODE + ErrorCode.PARAMETER_ERROR.getValue());
            String defaultMessage = result.getFieldError().getDefaultMessage();
            response.setMessage(defaultMessage);
        } else if (!request.getToken().equals(configuration.iFlyConfiguration.getToken())) {
            response.setErrorCode(BASE_CODE + ErrorCode.VERIFY_TOKEN_FAIL.getValue());
            response.setMessage("VERIFY_TOKEN_FAIL");
        } else {
            String sign = MiscUtil.iFlySign(MiscUtil.obj2Map(request), configuration.iFlyConfiguration.getSecret_key());
            String sign2 = MiscUtil.iFlySign(MiscUtil.obj2Map(request));
            if (!request.getSign().equals(sign) && !request.getSign().equals(sign2)) {
                response.setErrorCode(BASE_CODE + ErrorCode.VERIFY_SIGN_FAIL.getValue());
                response.setMessage("VERIFY_SIGN_FAIL");
            }
        }
        return response;
    }


/*=======================================监播===============================================*/


    @RequestMapping("/impress/begin")
    public void start(SimulateImpressArg impressArg, @RequestHeader(value = "User-Agent", required = false) String ua, HttpServletRequest request, HttpServletResponse response) {
        impressArg.setUrl(request.getRequestURL().toString() + "?" + request.getQueryString());
        impressArg.setIssuedTimeStr(SmlUtils.convert(impressArg.getIssuedTime()));
        simulateService.recordImpress(impressArg);
        response.setStatus(impressArg.getCode());
    }

    //结束监播
    @RequestMapping("/impress/end")
    public void end(SimulateImpressArg impressArg, @RequestHeader(value = "User-Agent", required = false) String ua, HttpServletRequest request, HttpServletResponse response) {
        impressArg.setUrl(request.getRequestURL().toString() + "?" + request.getQueryString());
        impressArg.setIssuedTimeStr(SmlUtils.convert(impressArg.getIssuedTime()));
        simulateService.recordImpress(impressArg);
        response.setStatus(impressArg.getCode());
    }

    //第三方通告
    @RequestMapping("/impress/win")
    public void win(SimulateImpressArg impressArg, @RequestHeader(value = "User-Agent", required = false) String ua, HttpServletRequest request, HttpServletResponse response) {
        impressArg.setUrl(request.getRequestURL().toString() + "?" + request.getQueryString());
        impressArg.setIssuedTimeStr(SmlUtils.convert(impressArg.getIssuedTime()));
        simulateService.recordImpress(impressArg);
        response.setStatus(impressArg.getCode());
    }


    @RequestMapping("/sign")
    public SimulateResponse<String> makeSign(@RequestBody Map<String, Object> map) {
        SimulateResponse<String> response = new SimulateResponse<String>();
        response.setErrorCode(ErrorCode.OK.getValue());
        String token = null;
        try {
            token = map.get("token").toString();
        } catch (Exception e) {
            response.setErrorCode(BASE_CODE + ErrorCode.TOKEN_NOT_FOUND.getValue());
            response.setMessage("TOKEN_NOT_FOUND");
            return response;
        }
        String sign = null;
        if (configuration.zmtConfiguration.getToken().equals(token)) {
            sign = MiscUtil.zmengSign(map);
        } else if (configuration.iFlyConfiguration.getToken().equals(token)) {
            sign = MiscUtil.iFlySign(map);
        } else {
            response.setErrorCode(BASE_CODE + ErrorCode.TOKEN_NOT_FOUND.getValue());
            response.setMessage("TOKEN_NOT_SUPPORT");
            return response;
        }
        response.setData(sign);
        return response;
    }


}
